package xredis

import (
	"github.com/gogf/gf/database/gredis"
	"github.com/gogf/gf/frame/g"
)

type redis struct {
	db *gredis.Redis
}

func DB(name ...string) *redis {
	if len(name) > 0 {
		return &redis{db: g.Redis(name[0])}
	}
	return &redis{db: g.Redis()}
}

// Set 写入
// expire 过期时间 秒
func (c *redis) Set(key string, val interface{}, expire ...int) error {
	_, err := c.db.DoVar("SET", key, val)
	if err != nil {
		return err
	}
	if len(expire) > 0 {
		_, err = c.db.DoVar("EXPIRE", key, expire[0])
		if err != nil {
			return err
		}
	}
	return nil
}

// Get 读取
func (c *redis) Get(key string) (v *g.Var) {
	v, _ = c.db.DoVar("GET", key)
	return v
}

// Del 删除
func (c *redis) Del(key string) error {
	_, err := c.db.DoVar("DEL", key)
	if err != nil {
		return err
	}
	return nil
}

// TTL 查看过期时间
func (c *redis) TTL(key string) int {
	v, _ := c.db.DoVar("TTL", key)
	return v.Int()
}

// Publish 发布订阅消息
func (c *redis) Publish(key string, msg interface{}) error {
	_, err := c.db.Do("PUBLISH", key, msg)
	return err
}

// INCR 自增1
func (c *redis) INCR(key string) int {
	v, _ := c.db.DoVar("INCR", key)
	return v.Int()
}

// DECR 自减1
func (c *redis) DECR(key string) int {
	v, _ := c.db.DoVar("DECR", key)
	return v.Int()
}

// 设置过期时间 秒
func (c *redis) Expire(key string, expire int) error {
	_, err := c.db.DoVar("EXPIRE", key, expire)
	return err
}

// 取消过期时间
func (c *redis) Persist(key string) {
	_, _ = c.db.DoVar("PERSIST", key)
}
//--------------------------------------
// 添加数据
func (c *redis) Zadd(key string, val1 int, val2 int) int {
	v, _ := c.db.DoVar("ZADD", key, val1,val2)
	return v.Int()
}
// 获取总数
func (c *redis) Zcard(key string) int {
	v, _ := c.db.DoVar("ZCARD", key)
	return v.Int()
}
// 删除指定元素
func (c *redis) Zrem(key string, val1 int, val2 int) int {
	v, _ := c.db.DoVar("ZREM", key, val1,val2)
	return v.Int()
}